<template>
    <section class="w-full h-full flex gap-col-4">
        <div class="flex-1 flex flex-col gap-row-4">
            <div class="bg-white box-border pa-4">
                <Query v-model:model="queryParameter" @query="query" @reset="reset" />
            </div>
            <div class="flex-1 bg-white box-border pa-4 flex flex-col">
                <div class="w-full pb-4 box-border flex items-center justify-between">
                    <div class="inline-flex items-center gap-col-2">
                        <n-button @click="insertData" type="primary">添加数据</n-button>
                        <n-button @click="batchDeleteData">批量删除</n-button>
                    </div>
                    <TableOperator @refresh="query" v-model:list="selectList" />
                </div>
                <NDataTable
                    class="flex-1 h-full"
                    :columns="columnList"
                    :data="data"
                    :loading="loading"
                    :row-key="(row: Data) => row.identity"
                    :striped="true"
                    :bordered="true"
                    :flex-height="true"
                    :single-line="false"
                    v-model:checked-row-keys="keyList"
                >
                </NDataTable>
            </div>
        </div>
        <n-modal
            v-model:show="formVisible"
            :auto-focus="false"
            :close-on-esc="false"
            preset="card"
            :style="{width: '800px'}"
            :title="formTitle"
            size="large"
            :bordered="false"
            :segmented="{content: 'soft', footer: 'soft'}">
            <data-form :identity="dataInfo.identity" @confirm="formConfirm" @cancel="formCancel" />
        </n-modal>

    </section>

</template>

<script setup lang="ts">
import {Api} from '@/api/type'
import Query from './data-query.vue'
import {h, onMounted, ref} from 'vue'
import DataForm from './data-form.vue'
import {BaseApi} from '@/api/base-api'
import {useTable} from '@/hook/use-table'
import {TableColumn} from 'naive-ui/es/data-table/src/interface'
import TableOperator from '@/component/common/table-operator.vue'
import {NButton, NDataTable, NModal, NSpace, useDialog, useMessage} from 'naive-ui'
// -------------------------------------------------
type R<T> = Api.Common.R<T>;
type Data = Api.System.DictData;
type PageParameter = Api.Common.PageParameter<Data>;
// -------------------------------------------------
const {code} = defineProps({
    code: {
        type: String,
        default: ''
    }
})

const dialog = useDialog()
const message = useMessage()
const baseApi = new BaseApi<Data>('dict-data')
const formTitle = ref<string>('')
const formVisible = ref<boolean>(false)
const dataTreeRef = ref()

const dataInfo = ref<Partial<Data>>({})
const {
    data,
    loading,
    getData,
    keyList,
    columnList,
    selectList,
    queryParameter,
    resetParameter
} = useTable<Data, TableColumn<Data>>({
    queryFn: async (query: PageParameter): Promise<R<Array<Data>>> => {
        let result: R<Array<Data>> = await baseApi.getDataList(query)
        if (result.code == 0) {
            return result
        } else {
            throw Error(result.message)
        }
    },
    queryParameter: {
        parent: code,
        name: ''
    },
    columnList: () => [
        {
            type: 'selection',
            title: '选择列',
            align: 'center',
            titleAlign: 'center',
            width: 50
        },
        {
            title: '字典名称',
            key: 'name',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '字典标识',
            key: 'code',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '字典数据',
            key: 'value',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '数据排序',
            key: 'sort',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '操作',
            key: 'operate',
            width: '160',
            align: 'center',
            titleAlign: 'center',
            render(row: Data) {
                return h(NSpace, {'justify': 'space-around'}, {
                        default: () => [
                            h(NButton, {onClick: () => updateData(row), size: 'small', type: 'primary', strong: true, secondary: true}, {default: () => '修改'}),
                            h(NButton, {onClick: () => deleteData(row), size: 'small', type: 'error', strong: true, secondary: true}, {default: () => '删除'})
                        ]
                    }
                )
            }
        }
    ] as TableColumn<Data>[]
})

async function reset() {
    resetParameter()
    await getData()
}

async function query() {
    await getData()
}

/**
 * 添加数据
 */
async function insertData() {
    dataInfo.value = {parent: code}
    formTitle.value = '添加数据'
    formVisible.value = true
}

/**
 * 更新数据
 */
async function updateData(item: Data) {
    dataInfo.value = item
    formTitle.value = '修改数据'
    formVisible.value = true
}

/**
 * 删除数据
 */
async function deleteData(item: Data) {
    await new Promise((resolve, reject) => {
        dialog.warning({
            title: '提示',
            content: '确定要删除选中数据?',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => resolve(true),
            onNegativeClick: () => reject(false)
        })
    }).then(async () => {
        let result = await baseApi.removeData(item.identity)
        if (result.code == 0) {
            message.success('删除数据成功.')
        } else {
            message.error('删除数据失败.' + (result.message || ''))
        }
    }).finally(async () => {
        await getData()
    })
}

/**
 * 批量删除数据
 */
async function batchDeleteData() {
    if (keyList.value.length == 0) {
        message.error('请先选择要删除的数据后再试')
        return false
    }
    await new Promise((resolve, reject) => {
        dialog.warning({
            title: '提示',
            content: '确定要删除选中数据?',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick() {
                resolve(true)
            },
            onNegativeClick() {
                reject(false)
            }
        })
    }).then(async () => {
        let result = await baseApi.batchRemoveData(keyList.value)
        if (result.code == 0) {
            message.success('删除数据成功.')
        } else {
            message.error('删除数据失败.' + (result.message || ''))
        }
    }).finally(async () => {
        await getData()
    })
}

async function formConfirm() {
    formVisible.value = false
    await getData()
    dataTreeRef.value?.initialize()
}

async function formCancel() {
    formVisible.value = false
    await getData()
    dataTreeRef.value?.initialize()
}

async function initialize() {
    if (code) {
        await getData()
    }
}

onMounted(async () => {
    await initialize()
})
</script>
